package com.woniuxy.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.annotation.MultiRequestBody;
import com.woniuxy.exception.customException.AccountIsUnpermitted;
import com.woniuxy.exception.customException.UpdateFailedException;
import com.woniuxy.resultCode.Result;
import com.woniuxy.resultCode.ResultCode;
import com.woniuxy.system.entity.PerformancePost;
import com.woniuxy.system.entity.PerformanceUser;
import com.woniuxy.system.service.PerformancePostService;
import com.woniuxy.system.service.PerformanceUserService;
import com.woniuxy.system.view.PerformanceUserView;
import com.woniuxy.utils.JwtUtil;
import com.woniuxy.utils.RedisUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 用户表	 前端控制器
 * </p>
 *
     * @since 2022-06-01
 */
@RestController
@RequestMapping("/system/performanceUser")
@Slf4j
public class PerformanceUserController {
    @Autowired
    PerformanceUserService userService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    PerformancePostService performancePostService;

    @PostMapping("/login")

    public Result login(@MultiRequestBody PerformanceUser user) throws AccountIsUnpermitted {
        LambdaQueryWrapper<PerformanceUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(user.getAccount()),PerformanceUser::getAccount,user.getAccount());
        wrapper.eq(StringUtils.isNotBlank(user.getPassword()),PerformanceUser::getPassword,user.getPassword());
        PerformanceUser one = userService.getOne(wrapper);
        if(one.getStatus().equals("F")){
            throw new AccountIsUnpermitted();
        }
        if(one==null){
            return Result.error().message("哥们，用户名密码都不知道还想登录？");
        }

        long currentTimeMillis = System.currentTimeMillis();
//        Md5Hash md5Hash = new Md5Hash(user.getPassword() ,user.getAccount(),10);
//        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getAccount(), md5Hash.toString());
        String token= JwtUtil.createToken(user.getAccount(),currentTimeMillis);
        redisUtil.set(one.getAccount(),currentTimeMillis,60*30);
        Long postId = one.getPostId();
        LambdaQueryWrapper<PerformancePost> performancePostLambdaQueryWrapper = new LambdaQueryWrapper<>();
        performancePostLambdaQueryWrapper.eq(PerformancePost::getId,postId);
        PerformancePost postInfo = performancePostService.getOne(performancePostLambdaQueryWrapper);
        return Result.ok().message("哥们，登录成功了！").data("token",token).data("userinfo",one).data("postInfo",postInfo);
    }

    @GetMapping("/logout")
    Result logout(){
        try{
            SecurityUtils.getSubject().logout();
        }
        catch (Exception e){
            return Result.error().message("我也不知道为什么等出失败,要么试试重新登录？");
        }
        return Result.ok().message("我糙，这么早就要退出了吗");
    }

    @ApiOperation("获取所有员工信息")
    @PostMapping("/getUser")
    @RequiresAuthentication
    public Result list(@MultiRequestBody(required = false)
                               PerformanceUserView performanceUserView
                                ,@MultiRequestBody(required = false)  String userid){
        log.info("获取参数:{}",userid);
        if(com.baomidou.mybatisplus.core.toolkit.StringUtils.checkValNull(performanceUserView.getCurrentPage())
                && com.baomidou.mybatisplus.core.toolkit.StringUtils.checkValNull(performanceUserView.getPageSize())){
            List<PerformanceUser> list = userService.list();
            return Result.ok().data("msg",list);
        }
        QueryWrapper<PerformanceUser> wrapper = getWrapper(performanceUserView);
        Page<PerformanceUser> page=new Page<>(performanceUserView.getCurrentPage(),performanceUserView.getPageSize());
        Page<PerformanceUser> result = userService.getAllPerformanceUser(page, wrapper);
        List<PerformanceUser> records = result.getRecords();
        long total = result.getTotal();
        long totalPages = result.getPages();
        log.info("返回数据:total{},totalPages{}",total,totalPages);
        return Result.ok().data("msg",records).data("total",total).data("totalPages",totalPages);
    }

    @ApiOperation("新增员工")
    @PostMapping("/add")
    @RequiresAuthentication
    public Result add(@MultiRequestBody PerformanceUser performanceUser,@MultiRequestBody String userid){
        boolean flag = userService.addPerformanceUser(performanceUser,userid);
        if (flag){
            return Result.ok();
        }else {
            return Result.error();
        }
    }

    @ApiOperation("通过id删除员工")
    @DeleteMapping("/delete/{id}")
    @RequiresAuthentication
    @RequiresRoles(value={"1","2","3"},logical = Logical.OR)
    public Result deleteById(@PathVariable Long id){
        boolean flag = userService.removeById(id);
        if (flag){
            return Result.ok();
        }else {
            return Result.error()
                    .code(ResultCode.DELETE_ERROR
                            .getCode())
                                    .message(ResultCode.DELETE_ERROR
                                           .getMessage());
        }
    }

    @ApiOperation("更新员工")
    @PostMapping("/update")
    @RequiresRoles(value={"1","2","3"},logical = Logical.OR)
    public Result update(@MultiRequestBody PerformanceUser performanceUser) throws UpdateFailedException {
        boolean flag = userService.updateById(performanceUser);
        if (!flag){
            throw new UpdateFailedException();
        }else {
            return  Result.ok().message("更新成功");
        }
    }

    @ApiOperation(("修改员工状态"))
    @PostMapping("/alterUserStatus")
    @RequiresRoles(value={"1","2","3"},logical = Logical.OR)
    public Result alterUserStatus(@MultiRequestBody String status,@MultiRequestBody String id) throws UpdateFailedException {
        UpdateWrapper<PerformanceUser> performanceUserUpdateWrapper = new UpdateWrapper<>();
        performanceUserUpdateWrapper.eq("id",id);
        performanceUserUpdateWrapper.set("status",status);
        boolean update = userService.update(performanceUserUpdateWrapper);
        if(!update){
            throw new UpdateFailedException();
        }
        return Result.ok().message("更新成功");
    }

    //封装queryWrapper
    private QueryWrapper<PerformanceUser> getWrapper(PerformanceUserView performanceUserView){
        QueryWrapper<PerformanceUser> queryWrapper=new QueryWrapper<>();
        assert performanceUserView != null;
        if(com.baomidou.mybatisplus.core.toolkit.StringUtils
                .isNotBlank(performanceUserView.getAccount())){
            queryWrapper.like("t.u_account",performanceUserView.getAccount()) ;}
        if(com.baomidou.mybatisplus.core.toolkit.StringUtils
                .isNotBlank(performanceUserView.getName())){
            queryWrapper.like("t.u_name",performanceUserView.getName()) ; }
        if(com.baomidou.mybatisplus.core.toolkit.StringUtils
                .isNotBlank(performanceUserView.getDepartmeId())){
            queryWrapper.eq("t.departme_id",performanceUserView.getDepartmeId()) ; }
        if(com.baomidou.mybatisplus.core.toolkit.StringUtils
                .isNotBlank(performanceUserView.getPostId())){
            queryWrapper.eq("t.post_id",performanceUserView.getPostId()) ; }
        return queryWrapper;
    }

}

